package com.ptszyxx.popose.module.main.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;

import com.ptszyxx.popose.BR;
import com.ptszyxx.popose.R;
import com.ptszyxx.popose.common.enums.HomeTabEnum;
import com.ptszyxx.popose.common.utils.YBusUtil;
import com.ptszyxx.popose.common.utils.YVoiceUtil;
import com.ptszyxx.popose.databinding.FragmentHomeTabBinding;
import com.ptszyxx.popose.databinding.FragmentHomeWorldBinding;
import com.ptszyxx.popose.module.main.home.adapter.HomeAdapter;
import com.ptszyxx.popose.module.main.home.adapter.HomeWorldAdapter;
import com.ptszyxx.popose.module.main.home.vm.HomeTabVM;
import com.ptszyxx.popose.module.main.home.vm.HomeWorldVM;
import com.ysg.base.BaseFragment;
import com.ysg.http.data.AppViewModelFactory;
import com.ysg.http.data.entity.home.HomeResult;
import com.ysg.utils.YCollectionUtil;

import java.util.List;

public class HomeWorldFragment extends BaseFragment<FragmentHomeWorldBinding, HomeWorldVM> {
    private HomeWorldAdapter adapter;
    private HomeTabEnum tabEnum;

    public HomeWorldFragment(HomeTabEnum tabEnum){
        this.tabEnum = tabEnum;
    }

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_home_world;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public HomeWorldVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(HomeWorldVM.class);
    }

    @Override
    public void onPause() {
        super.onPause();
        YVoiceUtil.getInstance().stopPlay();
    }

    @Override
    public void initView() {
        super.initView();
    }

    public void initAdapter() {
        adapter = new HomeWorldAdapter(viewModel, tabEnum);
        binding.refreshView.initAdapterStagger(adapter, 2);
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.tabEnum = tabEnum;
        viewModel.requestList(true);
    }

    @Override
    public void initViewObservable() {
        viewModel.uc.onRefreshEvent.observe(this, list -> setAdapterData((List<HomeResult>)list));
    }

    private void setAdapterData(List<HomeResult> list){
        binding.refreshView.setAdapterUI(adapter, list,  HomeTabEnum.account == tabEnum? true: viewModel.page == 1);
        YBusUtil.refreshHomeTabFinish(YCollectionUtil.isEmpty(list)? true: false, tabEnum);
    }

}
